const system = require('../../utils/system.js');
const api = require('../../utils/api.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: 0,
    bottomSafeHeight: 0,
    messageType: '', // 留言类型
    messageContent: '', // 留言内容
    images: [], // 上传的图片
    canSubmit: false, // 是否可以提交
    messages: [],
    loading: true,
    refreshing: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    inputContent: '',
    inputFocus: false,
    replyTo: null, // 回复的留言ID
    replyToName: '', // 回复的用户名
    messageRecords: [], // 留言记录
    loadingRecords: true, // 是否正在加载记录
    hasMoreRecords: true, // 是否有更多记录
    recordPage: 1, // 记录页码
    recordPageSize: 5, // 每页记录数量
    isEmpty: false, // 新增：是否为空数据状态
    // 模拟留言列表数据
    messageList: [
      {
        id: 1,
        type: '建议',
        content: '希望能增加更多题目类型',
        reply: '感谢您的建议,我们会继续完善题库',
        createTime: '2024-01-15 14:30:00',
        replyTime: '2024-01-15 15:00:00',
        status: '已回复'
      },
      {
        id: 2, 
        type: '问题',
        content: '为什么我的积分没有增加?',
        reply: '',
        createTime: '2024-01-16 10:20:00',
        replyTime: '',
        status: '待回复'
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('页面加载');
    this.setData({
      statusBarHeight: system.statusBarHeight || 20,
      bottomSafeHeight: system.bottomSafeHeight || 0
    });
    
    this.loadMessages();
    
    // 加载留言记录
    this.loadMessageRecords();
  },

  /**
   * 加载留言数据
   */
  async loadMessages(refresh = false) {
    console.log('加载留言列表, refresh:', refresh);
    if (refresh) {
      this.setData({
        page: 1,
        hasMore: true,
        messages: []
      });
    }
    
    if (!this.data.hasMore && !refresh) return;
    
    this.setData({
      loading: true,
      isEmpty: false
    });
    
    try {
      console.log('调用 getMessageList API, 页码:', this.data.page);
      const result = await api.getMessageList(this.data.page, this.data.pageSize);
      console.log('API 返回结果:', result);
      
      const records = Array.isArray(result) ? result : (result && result.records ? result.records : []);
      
      const processedRecords = records.map(record => {
        let content = record.content;
        let images = record.images;
        let reply = record.reply;

        try {
          // 处理图片数组
          if (typeof images === 'string') {
            try {
              images = JSON.parse(images);
            } catch (e) {
              console.error('解析图片数据失败:', e);
              images = [];
            }
          } else if (Array.isArray(images)) {
            images = images;
          } else {
            images = [];
          }

          // 确保每个图片URL都是完整的
          images = images.map(url => {
            if (url && typeof url === 'string') {
              if (url.startsWith('/uploads/')) {
                return `http://localhost:8080${url}`;
              } else if (!url.startsWith('http')) {
                return `http://localhost:8080/uploads/${url}`;
              }
            }
            return url;
          }).filter(url => url && typeof url === 'string');

          console.log('处理后的图片数组:', images);
        } catch (e) {
          console.error('处理消息数据失败:', e);
          content = record.content || '';
          reply = record.reply || '';
          images = [];
        }

        return {
          ...record,
          content,
          reply,
          images
        };
      });
      
      console.log('处理后的记录:', processedRecords);
      
      // 处理空数据情况
      const isEmpty = refresh ? processedRecords.length === 0 : this.data.messages.length === 0 && processedRecords.length === 0;
      
      this.setData({
        messages: refresh ? processedRecords : [...this.data.messages, ...processedRecords],
        loading: false,
        refreshing: false,
        hasMore: processedRecords.length === this.data.pageSize,
        page: this.data.page + 1,
        isEmpty: isEmpty
      });

      if (isEmpty) {
        wx.showToast({
          title: '暂无留言',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('加载留言失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      this.setData({
        loading: false,
        refreshing: false,
        isEmpty: this.data.messages.length === 0
      });
    }
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.setData({
      refreshing: true
    });
    
    this.loadMessages(true);
  },

  /**
   * 加载更多留言
   */
  loadMoreMessages() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadMessages();
    }
  },

  /**
   * 输入框内容变化
   */
  onInputChange(e) {
    const value = e.detail.value;
    console.log('输入内容变化:', value);
    this.setData({
      inputContent: value,
      messageContent: value
    }, () => {
      this.checkCanSubmit();
    });
  },

  /**
   * 显示回复输入框
   */
  replyToMessage(e) {
    const { id, username } = e.currentTarget.dataset;
    console.log('回复留言:', { id, username });
    this.setData({
      replyTo: id,
      replyToName: username,
      inputFocus: true
    });
  },

  /**
   * 取消回复
   */
  cancelReply() {
    console.log('取消回复');
    this.setData({
      replyTo: null,
      replyToName: '',
      inputFocus: false
    });
  },

  /**
   * 点赞/取消点赞
   */
  toggleLike(e) {
    const id = e.currentTarget.dataset.id;
    const messages = [...this.data.messages];
    const messageIndex = messages.findIndex(m => m.id === id);
    
    if (messageIndex !== -1) {
      const message = messages[messageIndex];
      const liked = !message.liked;
      
      // 更新点赞状态和数量
      messages[messageIndex].liked = liked;
      messages[messageIndex].likeCount = liked 
        ? (message.likeCount || 0) + 1 
        : Math.max((message.likeCount || 1) - 1, 0);
      
      this.setData({
        messages: messages
      });
      
      // 模拟API请求
      wx.showToast({
        title: liked ? '点赞成功' : '已取消点赞',
        icon: 'success'
      });
    }
  },

  /**
   * 删除留言
   */
  deleteMessage(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这条留言吗？',
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用删除API
          const messages = this.data.messages.filter(m => m.id !== id);
          
          this.setData({
            messages: messages
          });
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  /**
   * 删除回复
   */
  deleteReply(e) {
    const replyId = e.currentTarget.dataset.id;
    const parentId = e.currentTarget.dataset.parentId;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这条回复吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟删除
          const messages = [...this.data.messages];
          const messageIndex = messages.findIndex(m => m.id === parentId);
          
          if (messageIndex !== -1 && messages[messageIndex].replies) {
            messages[messageIndex].replies = messages[messageIndex].replies.filter(r => r.id !== replyId);
            
            this.setData({
              messages: messages
            });
            
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
          }
        }
      }
    });
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 选择留言类型
   */
  selectType(e) {
    const type = e.currentTarget.dataset.type;
    console.log('选择留言类型:', type);
    this.setData({
      messageType: type
    }, () => {
      this.checkCanSubmit();
    });
  },

  /**
   * 留言内容输入
   */
  onContentInput(e) {
    this.setData({
      messageContent: e.detail.value
    }, this.checkCanSubmit);
  },

  /**
   * 选择图片
   */
  async chooseImage() {
    if (this.data.images.length >= 3) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await wx.chooseMedia({
        count: 3 - this.data.images.length,
        mediaType: ['image'],
        sourceType: ['album', 'camera']
      });

      wx.showLoading({ title: '上传中...' });

      const uploadTasks = res.tempFiles.map(file => api.uploadImage(file.tempFilePath));
      const uploadResults = await Promise.all(uploadTasks);
      
      // 处理上传结果
      console.log('图片上传成功:', uploadResults);
      
      // uploadImage现在已返回完整URL，无需额外处理
      this.setData({
        images: [...this.data.images, ...uploadResults]
      });

      wx.hideLoading();
    } catch (error) {
      console.error('选择或上传图片失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '上传失败',
        icon: 'error'
      });
    }
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: this.data.images
    });
  },

  /**
   * 删除图片
   */
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    
    this.setData({
      images: images
    });
  },

  /**
   * 检查是否可以提交
   */
  checkCanSubmit() {
    const content = this.data.inputContent.trim() || this.data.messageContent.trim();
    const canSubmit = content.length > 0;
    
    console.log('检查是否可以提交:', { content, canSubmit });
    this.setData({
      canSubmit: canSubmit
    });
  },

  /**
   * 加载留言记录
   */
  loadMessageRecords(loadMore = false) {
    if (!loadMore) {
      this.setData({
        recordPage: 1,
        messageRecords: [],
        hasMoreRecords: true
      });
    }
    
    if (!this.data.hasMoreRecords && loadMore) return;
    
    this.setData({
      loadingRecords: true
    });
    
    // 模拟API请求
    setTimeout(() => {
      // 生成模拟数据
      const records = this.getMockRecords(this.data.recordPage, this.data.recordPageSize);
      
      this.setData({
        messageRecords: loadMore ? [...this.data.messageRecords, ...records] : records,
        loadingRecords: false,
        hasMoreRecords: records.length === this.data.recordPageSize,
        recordPage: this.data.recordPage + 1
      });
    }, 1000);
  },

  /**
   * 加载更多记录
   */
  loadMoreRecords() {
    this.loadMessageRecords(true);
  },

  /**
   * 生成模拟留言记录
   */
  getMockRecords(page, pageSize) {
    const records = [];
    const startIndex = (page - 1) * pageSize;
    
    // 只在前两页生成数据，模拟没有更多数据的情况
    if (page > 2) return [];
    
    for (let i = 0; i < pageSize; i++) {
      const id = startIndex + i + 1;
      const hasReply = Math.random() > 0.3; // 70%的概率有回复
      
      records.push({
        id: id,
        type: Math.random() > 0.5 ? '类型1' : '类型2',
        content: `这是第${id}条留言内容，描述了一些问题或者建议。`,
        time: this.getRandomTime(),
        status: hasReply ? '已回复' : '待回复',
        images: this.getRandomImages(),
        reply: hasReply ? `感谢您的留言，我们已经收到并处理了您的问题。如有其他疑问，请继续留言。` : '',
        replyTime: hasReply ? this.getRandomTime(true) : ''
      });
    }
    
    return records;
  },

  /**
   * 生成随机时间
   */
  getRandomTime(isReply = false) {
    const now = new Date();
    const days = isReply ? Math.floor(Math.random() * 2) : Math.floor(Math.random() * 7);
    const hours = Math.floor(Math.random() * 24);
    const minutes = Math.floor(Math.random() * 60);
    
    const date = new Date(now.getTime() - (days * 24 * 60 * 60 * 1000) - (hours * 60 * 60 * 1000) - (minutes * 60 * 1000));
    
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  /**
   * 生成随机图片数组
   */
  getRandomImages() {
    const images = [];
    const count = Math.floor(Math.random() * 4); // 0-3张图片
    
    for (let i = 0; i < count; i++) {
      // 使用随机颜色的占位图
      const color = Math.floor(Math.random() * 16777215).toString(16);
      images.push(`https://via.placeholder.com/200/${color}/ffffff`);
    }
    
    return images;
  },

  /**
   * 预览留言记录中的图片
   */
  previewRecordImage(e) {
    const current = e.currentTarget.dataset.current;
    const urls = e.currentTarget.dataset.urls;
    
    wx.previewImage({
      current: current,
      urls: urls
    });
  },

  // 加载留言记录
  async loadMessageRecords() {
    try {
      this.setData({ loadingRecords: true });
      const messages = await api.getMessageList();
      
      // 格式化时间
      const formattedMessages = messages.map(msg => ({
        ...msg,
        time: this.formatTime(msg.createTime),
        replyTime: msg.replyTime ? this.formatTime(msg.replyTime) : ''
      }));
      
      this.setData({
        messageRecords: formattedMessages,
        loadingRecords: false,
        hasMoreRecords: false // 暂时不实现分页
      });
    } catch (error) {
      console.error('加载留言失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      this.setData({ loadingRecords: false });
    }
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  },

  /**
   * 提交留言
   */
  async submitMessage() {
    console.log('开始提交留言');
    const content = this.data.inputContent.trim() || this.data.messageContent.trim();
    console.log('提交的内容:', content);
    
    if (!content) {
      wx.showToast({
        title: '请输入留言内容',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '发送中...',
      mask: true
    });
    
    try {
      // 图片URL已经是完整URL，不需要额外处理
      const messageData = {
        content: content,
        type: '留言',
        status: '未回复',
        images: this.data.images || [] // 直接使用完整URL数组
      };
      
      console.log('准备发送的留言数据:', messageData);
      const result = await api.publishMessage(messageData);
      console.log('留言发送结果:', result);
      
      wx.hideLoading();
      
      if (!result) {
        throw new Error('发送失败，服务器没有返回数据');
      }
      
      // 重置表单
      this.setData({
        messageType: '',
        messageContent: '',
        images: [],
        inputContent: '',
        replyTo: null,
        replyToName: '',
        isEmpty: false,
        canSubmit: false
      });
      
      wx.showToast({
        title: '发送成功',
        icon: 'success'
      });
      
      // 延迟刷新留言列表
      setTimeout(() => {
        this.loadMessages(true);
      }, 500);
    } catch (error) {
      console.error('提交留言失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '发送失败',
        icon: 'error',
        duration: 2000
      });
    }
  },

  // 预览留言中的图片
  previewRecordImage(e) {
    const { urls, current } = e.currentTarget.dataset;
    wx.previewImage({
      urls: urls,
      current: current
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
}); 